<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Test</title>
</head>
<body>
    <div>
        <input type="file" name="file" onchange="uploadFile(this);">
    </div>
    <div>
        <pre id="res-content"></pre>
    </div>
    
</body>
<script>
    function uploadFile(t){
        if(t.files.length<=0) return;
        let fm = new FormData();          //form标签中name的接口
        fm.append('file',t.files[0]);     //file:对应标签中name的属性

        //发起请求
        fetch('/upload',{
            method:'POST',
            body:fm
        })
        .then(res=>{
            if(res.ok){
                return res.text();
            }
            throw new Error(`${res.status} ${res.statusText}`)
        })
        .then(text =>{
            //document.getElementById('res-content').innerHTML = text
            let d = document.getElementById('res-content')
            d.innerHTML = `<img src='/image/${text}' style='width:80%;height:auto;'>`;
            // 请求图片的地址， 触发浏览器发出get请求
        })
        .catch(err=>{
            console.error(err.message)
        })
    }
</script>
</html>